<?php
/**
 * 账单组业务类
 * @author solar
 */
class GroupService
{
	/**
	 * 创建基本账单组，组中只有当前用户
	 * @author solar
	 * @param $group_name
	 * @param $user_id
	 * @param $is_default
	 * @return $group_id OR false  
	 */
	public function createBase($group_name, $user_id, $is_default=0) {
		$group_id=ModelFactory::get('GroupModel')->create($group_name);
		if($group_id){
			ModelFactory::get('GroupUserModel')->create($group_id, $user_id, $is_default);
			ModelFactory::get('CheckoutModel')->newCheckout($group_id);
			return $group_id;
		}
		return false;
	}
	
	/**
	 * 我在组中是否有权限
	 * @author solar
	 * @param int $group_id
	 * @return boolean
	 */
	public function hasPrivilege($group_id) {
		return ModelFactory::get('GroupUserModel')->inGroup(CoreFactory::session()->get('user_id'),$group_id);
	}
	
	/**
	 * 添加账单组成员
	 * @author solar
	 * @param int $group_id
	 * @param int $user_id
	 * @return boolean
	 */
	public function addMember($group_id,$user_id) {
		$groupUserModel = ModelFactory::get('GroupUserModel');
		$result = $groupUserModel->create($group_id,$user_id,0);
		if($result){
			ModelFactory::get('GroupModel')->plusQuantity($group_id);
			$groupUserModel->setRandomDefault($user_id);
			return true;
		}else return false;
	}
	
	/**
	 * 移除账单组成员
	 * @author solar
	 * @param int $group_id
	 * @param int $user_id
	 * @return boolean
	 */
	public function removeMember($group_id,$user_id) {
		$groupUserModel = ModelFactory::get('GroupUserModel');
		$result = $groupUserModel->delete($group_id,$user_id);
		if($result){
			ModelFactory::get('GroupModel')->minusQuantity($group_id);
			$groupUserModel->setRandomDefault($user_id);
			return true;
		}else return false;
	}
		
	/**
	 * 判断账单组是否有未结账单
	 * @author solar
	 * @param int $group_id
	 * @return boolean
	 */
	public function hasUnCheckout($group_id) {
		$checkoutRow = ModelFactory::get('CheckoutModel')->getUncheckout($group_id);
		return floatval($checkoutRow['c_total'])>0 ? true : false;
	}
	
	/**
	 * 账单组设为不可见
	 * @author solar
	 * @param int $group_id
	 * @return void
	 */
	public function inactiveGroup($group_id) {
		ModelFactory::get('GroupModel')->inactive($group_id);
		$groupUserModel = ModelFactory::get('GroupUserModel');
		$groupUserModel->inactiveUsers($group_id);
		$list = $groupUserModel->getAll(array('g_id'=>$group_id));
		foreach($list as $row){
			$groupUserModel->setRandomDefault($row['u_id']);
			ServiceFactory::get('UserService')->checkHasGroup($row['u_id']);
		}
	}
			
}
